<template>
  <a-page searchDisabled bg="/statics/map.jpg">
    <!--<div slot="nav">-->
      <!--<login-nav></login-nav>-->
    <!--</div>-->
    <div class="row justify-center">
      <div class="q-my-xl border-radius-3 col-xl-4 col-lg-4 col-md-4 col-sm-6 q-pa-md bg-white">
        <h1 class="size-24">登录</h1>
          <q-input
            float-label="邮箱/手机"
            autofocus
            v-model="emailOrPhone"
            class="q-my-md"
            clearable></q-input>
          <q-input
            float-label="密码"
            v-model="password"
            type="password"
            class="q-my-md"></q-input>
        <div class="justify-center row q-mt-sm">
          <q-btn :disabled="$v.loginGroup.$invalid" color="primary" class="q-my-md full-width" @click="login">登录</q-btn>
        </div>
        <div class="row justify-center">
          <div class="col row items-center size-14"><q-checkbox v-model="session" label="自动登录" /></div>
          <div>
            <a href="/reset/">
              <q-btn dense color="primary" flat label="忘记密码"/>
            </a>
          </div>
        </div>
        <a-oauth></a-oauth>
        <div class="row q-mt-lg justify-center">
          <a href="/register"><q-btn color="primary" flat label="注册帐号"/></a>
        </div>
      </div>
    </div>
  </a-page>
</template>

<script>
  import { required, minLength, maxLength } from 'vuelidate/lib/validators'
  import { authMixin } from '../components/mixin/auth'
  import { mapState } from 'vuex'
  import LoginNav from './nav/login'

  export default {
    name: 'PageLogin',
    components: { LoginNav },
    mixins: [authMixin],
    data () {
      return {
        emailOrPhone: '',
        password: '',
        session: true
      }
    },
    validations: {
      emailOrPhone: {
        required, minLength: minLength(2), maxLength: maxLength(32)
      },
      password: {
        required, minLength: minLength(6), maxLength: maxLength(16)
      },
      loginGroup: ['emailOrPhone', 'password']
    },
    computed: {
      ...mapState(['history'])
    },
    methods: {
      async login () {
        const { status, data } = await this.postRequest({
          api: '/api/user/login/',
          data: {
            phone_or_email: this.emailOrPhone,
            password: this.password
          }
        })

        if (status === 200) {
          let redirectPath = '/'

          data.session = this.session

          this.authorize(data)
          for (let i = 0; i < this.history.length; i++) {
            const history = this.history[i]

            if (history.match(/^\/login/) || history.match(/^\/register/) || history.match(/^\/reset/)) {
              continue
            } else {
              redirectPath = history
              break
            }
          }

          this.$router.push(redirectPath)
        } else {
          this.notify('error', '登录失败，手机、邮箱或密码不正确')
        }
      }
    }
  }
</script>

<style lang="stylus">

</style>
